package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.vo.MemberRegisterVo;
import com.atguigu.gulimall.member.vo.SocialUserVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public void regist(MemberRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        //查询会员的默认等级
       MemberLevelEntity memberLevelEntity = memberLevelDao.selectMemberLevel();
       memberEntity.setLevelId(memberLevelEntity.getId());
       //检查用户名和手机号是否唯一
        checkUsernameUnique(vo.getUserName());
        checkPhoneUnique(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
        //密码加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(vo.getPassWord());
        memberEntity.setPassword(encode);
        memberEntity.setCreateTime(new Date());
        memberEntity.setNickname(vo.getUserName());
        //保存其他信息
        this.baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(count > 0){
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if(count > 0){
            throw new UsernameExistException();
        }
    }

    /**
     * 第三方登录
     * @param socialUserVo socialUserVo
     * @return R
     * @throws Exception
     */
    @Override
    public MemberEntity authLogin(SocialUserVo socialUserVo) throws Exception {
        //具有登录和注册逻辑
        String uid = socialUserVo.getUid();
        //1、判断当前社交用户是否已经登录过系统
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(memberEntity != null){
            //这个用户已经注册过
            //更新用户的访问令牌的时间和access_token
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUserVo.getAccess_token());
            update.setExpiresIn(String.valueOf(socialUserVo.getExpires_in()));
            //更新
            this.baseMapper.updateById(update);
            memberEntity.setAccessToken(socialUserVo.getAccess_token());
            memberEntity.setExpiresIn(String.valueOf(socialUserVo.getExpires_in()));
            return memberEntity;
        }else {
            //2、没有查到当前社交用户对应的记录我们就需要注册一个
            MemberEntity register = new MemberEntity();
            //不管是否查询成功都要继续执行
            try {
                //3、查询当前社交用户的社交账号信息（昵称、性别等）
                Map<String, String> headers = new HashMap<>();
                Map<String, String> querys = new HashMap<>();
                querys.put("access_token",socialUserVo.getAccess_token());
                querys.put("uid",socialUserVo.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", headers, querys);
                if(response.getStatusLine().getStatusCode() == 200){
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    String profileImageUrl = jsonObject.getString("profile_image_url");

                    register.setNickname(name);
                    register.setGender("m".equals(gender)?1:0);
                    register.setHeader(profileImageUrl);
                }

            } catch (Exception e) {}
            register.setCreateTime(new Date());
            register.setSocialUid(socialUserVo.getUid());
            register.setAccessToken(socialUserVo.getAccess_token());
            register.setExpiresIn(String.valueOf(socialUserVo.getExpires_in()));
            //把用户信息插入到数据库中
            this.baseMapper.insert(register);
            return register;
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }



}